<template>
  <div class="categories">
    <div class="container">
      <!-- 导航 -->
      <nav>
        <h3>{{selectOption}}</h3>
        <el-select v-model="selectValue" @change="handleValChange" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button type="primary" size="small" icon="el-icon-edit" @click="editGoodsType(1)"
          >编辑分类</el-button
        >
        <el-button type="success" size="small" icon="el-icon-plus" @click="addGoodsType(1)"
          >添加分类</el-button
        >
        <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteGoodsType(1)"
          >删除分类</el-button
        >
      </nav>
      <!-- 列表内容 -->
      <div class="cont">
        <!-- 表格列表 -->
        <div class="table_list">
          <table>
            <tr>
              <td colspan="5">
                <span>{{this.displayData.type_name}}</span>
                <el-button type="primary" size="small" icon="el-icon-edit" @click="editGoodsType(2)"
                    >编辑分类</el-button
                >
                <el-button type="success" size="small" icon="el-icon-plus" @click="addGoodsType(2)"
                  >添加分类</el-button
                >
                <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteGoodsType(2)"
                  >删除本栏</el-button
                >
              </td>
            </tr>
            <tr>
              <td>序号</td>
              <td>分类id</td>
              <td>分类名</td>
              <td>展示图片</td>
              <td>
                <span>操作</span>
                <el-button type="success" size="small" icon="el-icon-plus" @click="addGoodsType(3)"
                  >添加分类</el-button
                >
              </td>
            </tr>
            <template v-show="!thirdData.length">
              <tr v-for="(item, index) in thirdData" :key="index">
                <td>{{index+1}}</td>
                <td>{{item.good_type_id}}</td>
                <td>{{item.type_name}}</td>
                <td><img src="../assets/img/test.jpg" alt=""></td>
                <td>
                  <el-button 
                  type="primary" 
                  size="small" 
                  icon="el-icon-edit"
                  @click="editGoodsType(3, index, item.good_type_id, item.type_name)">
                  编辑
                  </el-button>
                  <el-button 
                  type="danger" 
                  size="small" 
                  icon="el-icon-delete"
                  @click="deleteGoodsType(3, item.good_type_id)">
                  删除
                  </el-button>
                </td>
              </tr>
            </template>
          </table>
        </div>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1]"
          :page-size="1"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="computPageLen">
        </el-pagination>
      </div>
      <!-- 编辑列表 -->
      <div class="edit_form" v-show="editFormIsShow">
        <div class="form">
          <p>
            <span>序号：</span>
            <input type="text" v-model="editFormCont.index" disabled >
          </p>
          <p>
            <span>id：</span>
            <input type="text" v-model="editFormCont.id" disabled >
          </p>
          <p>
            <span>分类名：</span>
            <input type="text" v-model="editFormCont.name">
          </p>
          <div>
            <el-button type="primary" size="small" @click="editGoodsType(0)">确认</el-button>
            <el-button type="info" size="small" @click="editFormSwitch">取消</el-button>
          </div>
        </div>
      </div>
      <!-- 添加列表 -->
      <div class="add_form" v-show="addFormIsShow">
        <div class="form">
          <p>
            <span>父级id：</span>
            <el-select v-model="addFormSelectVal" @change="addFormSeclectEvent" :disabled="addFormSelectIsDisabled" placeholder="请选择">
              <el-option
                v-for="item in addFormOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </p>
          <p>
            <span>分类名：</span>
            <input type="text" v-model="addFormCont.name">
          </p>
          <div>
            <el-button type="primary" size="small" @click="addGoodsType(0)">确认</el-button>
            <el-button type="info" size="small" @click="addFromSwitch">取消</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      token: null // token
      , data: [] // 分类列表（）
      , options: [] // select分类项 (value: good_type_id  label: type_name)
      , selectValue: 0 // 导航菜单选择结果(默认值为options第一项的value)
      , selectOption: "" // 菜单选中项(导航栏标题展示，默认值为options第一项的label)
      , currentPage: 1 // 当前页码
      , secData: "" // 二级分类数据
      , displayData: "" // 用于展示的二级分类项
      , thirdData: "" // 三级分类数据（表格展示项）
      , editFormCont: {index: 0, id: "", name: ""} // 编辑表单内容
      , editFormIsShow: false // 编辑表单切换
      , addFormOptions: [] // 添加表单select数据（value: good_type_id  label: type_name）
      , addFormSelectVal: "" // 添加表单select选中值（value）
      , addFormIsShow: false // 添加表单切换
      , addFormSelectIsDisabled: false // 添加表单select是否禁用
      , addFormCont: {pid: "", name: ""}
    }
  },

  methods: {
    // 获取分类列表
    getCategoriesList() {
      this.axios({
        method: "POST",
        url: "api/admin/goodsTypeList",
        data: {
          token: this.token
        }
      })
      .then( res => {
        console.log("分类列表为：", res.data.data)
        this.data = res.data.data
        // select菜单数据生成
        this.setSelectData(res.data.data)
        this.setDefaultData()
      })
      .catch( err => {
        console.log(err)
      })
    },
    
    // select菜单数据生成
    setSelectData(allData) {
      // 清空数据
      this.options = []
      allData.forEach( item => {
        if (item.parent_id === 0) {
          let obj = {
            value: item.good_type_id,
            label: item.type_name
          }
          this.options.push(obj)
        }
      })
    },
    
    // 默认数据设置
    setDefaultData() {
      console.log("select选项为：", this.options)
      this.selectValue = this.options[1].value
      this.selectOption = this.options[1].label
      // 二级分类数据筛选（secData）
      this.screenSecData(this.options[1].value)
      // 设置用于展示的二级分类项
      this.displayData = this.secData[0]
      console.log("展示项", this.displayData)
      // 三级分类数据筛选（thirdData）
      this.screenThirdData()
    },
    
    // select菜单val改变
    handleValChange(val) {
      console.log(val) 
      // 页码还原
      this.currentPage = 1
      // 数据筛选
      let matchItem = this.options.filter( item => {
        return item.value === val
      })
      // 导航显示信息改变
      this.selectOption = matchItem[0].label
      // 二级分类筛选（displayData）
      this.screenSecData(val)
      // 设置用于展示的二级分类项
      if (this.secData.length) this.displayData = this.secData[0]
      else this.displayData = {type_name: "请添加分类", good_type_id: -1}
      console.log("展示项", this.displayData)
      // 三级分类数据筛选（thirdData）
      this.screenThirdData()
    },
    
    // 二级分类数据筛选（secData）
    screenSecData(parent_id) {
      console.log(parent_id)
      this.secData = this.data.filter( item => {
        return item.parent_id === parent_id
      })
      console.log("二级分类数据：", this.secData)
    },
    
    // 三级分类数据筛选（thirdData）
    screenThirdData() {
      this.thirdData = this.data.filter( item => {
        return item.parent_id === this.displayData.good_type_id
      })
      console.log("三级分类数据为：",this.thirdData)
    },
    
    // 分页跳转
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val
      // 设置用于展示的二级分类项
      this.displayData = this.secData[this.currentPage-1]
      console.log("展示项", this.displayData)
      // 三级分类数据筛选（thirdData）
      this.screenThirdData()
    },
    
    // 删除分类(如果一级或者二级分类下面有三级分类，那么不允许直接删除一二级分类)
    deleteGoodsType(level, type_id) {
      let id = 0, toggle
      switch(level) {
        case 1:
          console.log("删除一级分类")
          id = this.selectValue
          toggle = this.data.some( item => {
            return item.parent_id === id
          })
          break
        case 2:
          console.log("删除二级分类")
          id = this.displayData.good_type_id
          toggle = this.data.some( item => {
            return item.parent_id === id
          })
          break
        case 3:
          console.log("删除三级分类")
          id = type_id
          break
      }
      if (toggle) {
         this.$message({
          message: '子类未完全删除',
          type: 'error',
          duration: 1000
        })
        return 
      }
      this.axios({
        method: "POST",
        url: "api/admin/deleteGoodtype",
        data: {
          token: this.token,
          id
        }
      })
      .then( res => {
        console.log(res.data)
        this.$message({
          message: '分类删除成功',
          type: 'success',
          duration: 1000
        })
        // 数据重渲染
        this.reGetCategoriesList()
      })
      .catch( err => {
        console.log(err)
      })
    },
    
    // 编辑分类
    editGoodsType(level, index, id, name) {
      switch(level) {
        case 1: // 编辑一级分类
          console.log("编辑一级分类")
          this.editFormCont.index = 0
          this.editFormCont.id = this.selectValue
          this.editFormCont.name = this.selectOption
          break
        case 2: // 编辑二级分类
          console.log("编辑二级分类")
          this.editFormCont.index = 0
          this.editFormCont.id = this.displayData.good_type_id
          this.editFormCont.name = this.displayData.type_name
          break
        case 3: // 编辑三级分类
          console.log("编辑三级分类")
          this.editFormCont.index = index+1
          this.editFormCont.id = id
          this.editFormCont.name = name
          break
        case 0: // 提交编辑请求
          console.log("提交编辑请求")
          // 发送请求
          this.axios({
            method: "POST",
            url: "api/admin/addGoodType",
            data: {
              token: this.token,
              name: this.editFormCont.name,
              id: this.editFormCont.id
            }
          })
          .then( res =>{
            console.log(res.data)
            // 数据重渲染
            this.reGetCategoriesList()
          })
          .catch( err =>{
            console.log(err)
          })
          break
      }
      // 编辑表单切换
      this.editFormSwitch()
    },
    
    // 新增类别
    addGoodsType(level){
      switch(level) {
        case 1:
          console.log("添加一级分类")
          this.addFormSelectIsDisabled = true
          this.addFormSelectVal = 0
          break
        case 2:
          console.log("添加二级分类")
          this.addFormSelectIsDisabled = false
          this.addFormSelectVal = ""
          // 添加表单select菜单数据生成
          this.addFormOptions = this.options
          break
        case 3:
          console.log("添加三级分类")
          this.addFormSelectIsDisabled = false
          this.addFormSelectVal = ""
          // 添加表单select菜单数据生成
          this.addFormSetSelectData()
          break
        case 0:
          console.log("提交添加请求")
          // 发送请求
          this.axios({
            method: "POST",
            url: "api/admin/addGoodType",
            data: {
              token: this.token,
              name: this.addFormCont.name,
              pid: this.addFormCont.pid
            }
          })
          .then( res =>{
            console.log(res.data)
            // 数据重渲染
            this.reGetCategoriesList()
          })
          .catch( err =>{
            console.log(err)
          })
          break
      }
      // 添加表单切换
      this.addFromSwitch()
    },
    
    // 添加表单select菜单数据生成
    addFormSetSelectData() {
      // 清空数据
      this.addFormOptions = []
      this.secData.forEach( item => {
        let obj = {
          value: item.good_type_id,
          label: item.type_name
        }
        this.addFormOptions.push(obj)
      })
    },
    
    // 添加表单select事件
    addFormSeclectEvent(val) {
      console.log(val)
      this.addFormCont.pid = val
    },
    
    // 编辑表单切换
    editFormSwitch() {
      this.editFormIsShow = !this.editFormIsShow
    },
    
    // 添加表单切换
    addFromSwitch() {
      this.addFormIsShow = !this.addFormIsShow
    },
    
    // 数据重渲染
    reGetCategoriesList() {
      this.axios({
        method: "POST",
        url: "api/admin/goodsTypeList",
        data: {
          token: this.token
        }
      })
      .then( res => {
        console.log("分类列表为：", res.data.data)
        this.data = res.data.data
        // select菜单数据生成
        this.setSelectData(res.data.data)
        // 二级、三级分类重筛选
        this.screenSecData(this.selectValue)
        this.screenThirdData()
        // 设置用于展示的二级分类项
        if (this.secData.length) this.displayData = this.secData[this.currentPage-1]
        else this.displayData = {type_name: "请添加分类", good_type_id: -1}
        // 判断当前是否删除的最后一个一级分类，是就跳转到上一个一级分类
        if (this.data.length > res.data.data.length) {
          console.log("最后一个id为：",this.options[this.options.length-1].value)
          this.selectValue = this.options[this.options.length-1].value
          this.selectOption = this.options[this.options.length-1].label
        }
      })
      .catch( err => {
        console.log(err)
      })
    }
    
  },
  
  computed: {
    // 计算分页长度(以二级分类数据为计算值)
    computPageLen() {
      return this.secData.length
    }
  },

  created() {
    // 数据初始化
    // this.secData = this.data[0]
    // this.thirdData = this.secData.type_options[0]
  },
  
  mounted() {
    this.token = this.$store.state.token
    this.getCategoriesList()
  }
};
</script>

<style lang="scss" scoped>
.categories {
  box-sizing: border-box;
  width: 100%;
  padding: 20px;
  background-color: #f1f3f2;

  .container {
    box-sizing: border-box;
    width: 100%;
    min-height: 100%;
    background-color: #fff;

    nav {
      display: flex;
      align-items: center;
      padding: 10px 20px;

      h3 {
        min-width: 120px;
        margin-right: 50px;
      }

      .el-select {
        margin-right: 20px;
      }
    }
    
    .cont {
      margin-top: 40px;
      
      .table_list {
        display: flex;
        justify-content: center;
        padding: 0 20px;
        
        table {
          flex: 1;
          border-collapse: collapse;
          
          td {
            padding: 6px 0;
            text-align: center;
            vertical-align: middle;
            color: #666;
            border: 1px solid rgba($color: #000000, $alpha: .1);
            
            span {
              margin-right: 10px;
              font-weight: bold;
              vertical-align: middle;
            }
          }
          
          img {
            width: 70px;
            height: 70px;
          }
        }
      }
      
      .el-pagination {
        display: flex;
        justify-content: center;
        margin-top: 40px;
      }
    }
    
    .edit_form,
    .add_form {
      position: fixed;
      top: 0;
      left: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background-color: transparent;
      
      .form {
        width: 350px;
        padding: 20px;
        transform: translateY(-50%);
        box-shadow: 0 0 10px 0 #ccc;
        background-color: #fff;
        
        p {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 0;
          margin-bottom: 20px;
          color: #999;
        
          input {
            width: 75%;
            height: 30px;
            text-indent: 1em;
            color: #999;
            border: 1px solid #ccc;
            outline: none;
          }
          
          .el-select {
            width: 75%;
          }
        }
        
        div {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
}
</style>
